# -*- coding:utf-8 -*-
# --author： jingfeng 
# time: 2019/3/9

from settings import *
import redis
from pickle import dumps,loads
from crawl import WeiXinRequests

REDIS_KEY = 'weixin'

class RedisQueue(object):
    def __init__(self, host=REDIS_HOST, port=REDIS_PORT,
                 password=REDIS_PASSWORD):
        """
        初始化
        :param host: Redis 地址
        :param port: Redis 端口
        :param password: Redis密码
        """
        self.db = redis.StrictRedis(host=host, port=port, password=password,
                                    decode_responses=True,db=1)


    def add(self, request):
        """
        向队列添加序列化后的Request
        :param request: 请求对象
        :param fail_time: 失败次数
        :return: 添加结果
        """
        if isinstance(request, WeiXinRequests):
            return self.db.rpush(REDIS_KEY, dumps(request))
        return False

    def pop(self):
        """
        取出下一个Request并反序列化
        :return: Request or None
        """
        if self.db.llen(REDIS_KEY):
            return loads(self.db.lpop(REDIS_KEY))
        else:
            return False

    def clear(self):
        self.db.delete(REDIS_KEY)

    def empty(self):
        return self.db.llen(REDIS_KEY) == 0
